/**
 * Captain
 * © 2018 Captain copyright，All rights reserved.
 * http://www.sccaptain.com.cn
 * 
 * JAVA : 8
 * 文  件  名: ImageController.java
 * 创  建  人: QinYoubin (qin.youbin@sccaptain.com.cn)
 * 创建时间: 2018年5月2日 上午10:51:41
 * 版         本: 1.0.0
 * 备         注:
 * 修订历史:
 */
package com.material.c2c.web.img.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.material.c2c.img.entity.TPXX;
import com.material.c2c.img.service.ImageService;
import com.material.c2c.util.SystemUtil;

/**
 * 图片控制器
 * @since 1.0
 * @version 1.0
 * @author QinYoubin (qin.youbin@sccaptain.com.cn)
 */
@Controller
@RequestMapping("/img")
public class ImageController {
  @Resource
  private ImageService imageService;
  
  @GetMapping("/pic/{id}")
  public void getPicture(@RequestBody String id,HttpServletResponse response) {
    TPXX tpxx = imageService.getOne(id);
    final String path = SystemUtil.getAttachmentPath() + tpxx.getTplj();

    response.setHeader("Pragma","No-cache");    

    response.setHeader("Cache-Control","no-cache");    

    response.setDateHeader("Expires", 0);    

    BufferedInputStream bis = null;  

    OutputStream os = null;  
    
    FileInputStream fileInputStream;  

    try {
      fileInputStream = new FileInputStream(new File(path));
      bis = new BufferedInputStream(fileInputStream);  

      byte[] buffer = new byte[512];  

      response.reset();  
      response.setCharacterEncoding("UTF-8");  

      //不同类型的文件对应不同的MIME类型  

      response.setContentType(tpxx.getMime());  
      response.setContentLength(bis.available());  
      os = response.getOutputStream();  
      int n;  

      while ((n = bis.read(buffer)) != -1) {  

        os.write(buffer, 0, n);  

      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        bis.close();
      } catch (IOException e) {
        e.printStackTrace();
      }  

      try {
        os.flush();
      } catch (IOException e) {
        e.printStackTrace();
      }  

      try {
        os.close();
      } catch (IOException e) {
        e.printStackTrace();
      } 
    }
  }
}
